﻿using CloudDcPc.Entity;
using CloudDcPc.util;
using CloudDcPc.Util;
using MYSQL_db.DAL;
using MYSQL_db.Model;
using MYSQL_db.Mwcard;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CloudDcPc
{
    /// <summary>
    /// CheckOut.xaml 的交互逻辑
    /// </summary>
    public partial class CheckOutDlg : Window
    {
        private Card card;

        private List<string> mOrder_nums = new List<string>();
        private List<int> mTab_nums = new List<int>();
        private List<string> mVips = new List<string>();
        private float mTrue_sum = 0;
        private float mTrue_sum_backup = 0;
        private float mPc_sum = 0;
        private float mTg_sum = 0;
        private Boolean cardFlag = true;
        private float mTemp_ml = 0;
        private float mTemp_ml_j = 0;
        private List<Order> mOrders;
        private List<string> mFood_type = new List<string>();
        private List<CheckOutGz> checkOutGzs = new List<CheckOutGz>();
        private StringUtil strUtil;
        List<int> list_order_id = new List<int>();

        public CheckOutDlg(string order_id, List<int> list_tab_num)
        {
            InitializeComponent();
            txt_cash.Focus();
            txt_cash.SelectAll();

            for (int i = 0; i < list_tab_num.Count; i++)
            {
                checkOutGzs.Add(new CheckOutGz());
            }
            checkOutGzs[0] = null;
            foreach (int i in list_tab_num)
            {
                list_order_id.Add(App.OrderBean.GetNowOrderIdByTabNum(i));
            }

            strUtil = new StringUtil();
            //取得所有批准人信息：type=3
            List<User> list_approver = App.UserBean.GetUsersByField("type", "3");
            cb_approver.ItemsSource = list_approver;
            //取得当前order实体
            mOrders = App.OrderBean.GetOrderById(list_order_id);
            //初始化全局变量
            foreach (Order o in mOrders)
            {
                mOrder_nums.Add(o.Order_num);
                mTab_nums.Add(o.Tab_num);
                txt_tab_namenum.Text += o.Tab_name + " ";
            }

            mFood_type = App.OrdersBean.GetTypeByOrderNum(mOrder_nums);  //食物种类
            //显示结账单号/桌号
            txt_checkout_num.Text = "C" + mOrder_nums[0];

            food_type_sp.Children.Clear();
            //循环显示食物详情
            for (int i = 0; i < mFood_type.Count; i++)
            {
                DataTable dt = App.OrdersBean.GetOrdersDataTableByOrderNumAndType(mOrder_nums, mFood_type[i]);

                Expander expander = new Expander();
                expander.Header = mFood_type[i] + "(" + dt.Rows.Count + "项," + App.OrdersBean.GetAllPriceByOrderNumOrType(mOrder_nums, mFood_type[i]) + "元)";
                expander.IsExpanded = true;

                DataGrid dg = new DataGrid();
                dg.FontSize = 15;
                dg.Margin = new Thickness(10, 5, 10, 10);
                dg.IsReadOnly = true;
                dg.ItemsSource = dt.DefaultView;

                expander.Content = dg;

                food_type_sp.Children.Add(expander);
            }
            //被退食物
            DataTable table = App.OrdersBean.GetReturnedOrdersDataTableByOrderNum(mOrder_nums);
            //如果有被退食物就显示相关金额
            if (table.Rows.Count > 0)
            {
                txt_returned_sum.Text = App.OrdersBean.GetReturnedOrdersSum(mOrder_nums).ToString();
                sp_returned.Visibility = Visibility.Visible;
            }
            else
            {
                sp_returned.Visibility = Visibility.Collapsed;
            }
            dg_returnedorders.ItemsSource = table.DefaultView;

            //总价格
            float all_final_price = App.OrdersBean.GetAllPriceByOrderNumOrType(mOrder_nums, "");
            //保存全局总价格
            mTrue_sum = mTrue_sum_backup = all_final_price - float.Parse(txt_returned_sum.Text);



            foreach (Order o in mOrders)
            {
                if (o.Together_name != "")
                {
                    GroupBox gb = new GroupBox();
                    gb.Header = o.Together_name + "(" + App.TogetherBean.GetTogetherByField("name", o.Together_name).Price + "元)";
                    DataGrid dg = new DataGrid();
                    dg.FontSize = 15;
                    dg.Margin = new Thickness(5);
                    dg.IsReadOnly = true;
                    DataTable tg_table = App.TogetherBean.GetOrdersByName(o.Together_name);
                    dg.ItemsSource = tg_table.DefaultView;

                    gb.Content = dg;

                    sp_all_tg.Children.Add(gb);

                    mTg_sum += App.TogetherBean.GetTogetherByField("name", o.Together_name).Price;
                }
            }

            //最后显示总价格
            txt_sum.Text = mTrue_sum + "";
            txt_all_final_price.Text = txt_sum.Text.Split('.')[0];
            mTemp_ml_j = float.Parse(strUtil.Round(mTrue_sum - float.Parse(txt_all_final_price.Text), 1) + "");

            txt_tg_sum.Text = txt_tg_sum2.Text = mTg_sum + "";

            //txt_tjc_price.Text = (App.OrdersBean.GetAllPriceByOrderNumAndFieldLike(mOrder_nums, "food_name", "[特]") - App.OrdersBean.GetAllReturnedPriceByOrderNumAndFieldLike(mOrder_nums, "food_name", "[特]")).ToString();
            txt_tjc_price.Text = (App.OrdersBean.GetAllSpecialPriceByOrderNumAndWhereString(mOrder_nums, 2) - App.OrdersBean.GetAllSpecialReturnedPriceByOrderNumAndWhereString(mOrder_nums, 2)).ToString();
            txt_jsyl_price.Text = (App.OrdersBean.GetAllSpecialPriceByOrderNumAndWhereString(mOrder_nums, 3) - App.OrdersBean.GetAllSpecialReturnedPriceByOrderNumAndWhereString(mOrder_nums, 3)).ToString();

            txt_qt_price.Text = (mTrue_sum - float.Parse(txt_jsyl_price.Text) - float.Parse(txt_tjc_price.Text)).ToString();

            //初始化
            txt_cash.Text = "0";
            discount_money.Text = "0";
        }




        /// <summary>
        /// 结账按钮
        /// </summary>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (pb_pwd.IsEnabled)
            {
                if (App.UserBean.VerifyUser(((User)cb_approver.SelectedItem).User_num, pb_pwd.Password) == 0)
                {
                    MessageBox.Show(((User)cb_approver.SelectedItem).User_num + ",授权密码错误！");
                    return;
                }

            }

            List<CheckOut> checkOuts = GetCheckOut();

            if (((Button)sender).Tag.ToString() == "0")
            {
                try
                {
                    PrintUtil printUtil = new PrintUtil();
                    printUtil.UsbPrintString(GetPrintStr(checkOuts, checkOutGzs, false));
                    return;
                }
                catch
                {
                    MessageBox.Show("打印出错！请检查打印机是否连接正确或者打印机名称是否为\"XP-80\"!");
                    return;
                }
            }

            if (float.Parse(txt_return_cash.Text) < 0)
            {
                MessageBox.Show("找零不能小于零！！", "提示");
                return;
            }

            string messageBoxText = "确认结账吗？";
            string caption = "结账";
            MessageBoxButton button = MessageBoxButton.YesNo;
            MessageBoxImage icon = MessageBoxImage.Question;
            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);
            if (result == MessageBoxResult.Yes)
            {
                if (checkOuts[0] == null)
                {
                    MessageBox.Show("请将信息填写完整！", "提示");
                    return;
                }

                if (checkOutGzs[0] != null)
                {
                    if (!App.CheckOutGzBean.AddCheckOutGz(checkOuts, checkOutGzs))
                    {
                        MessageBox.Show("结账失败！", "提示");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        App.CheckOutBean.AddCheckOut(checkOuts);
                    }
                    catch(Exception eee)
                    {
                         MessageBox.Show("结账失败！错误信息：\n"+eee.Message+"\n"+eee.Source+"\n"+eee.StackTrace, "提示");
                         return;
                    }
                }
                ///开始打印
                bool print_flag = true;
                while (print_flag)
                {
                    try
                    {
                        // MessageBox.Show(GetPrintStr(checkOuts, checkOutGzs));
                        PrintUtil printUtil = new PrintUtil();
                        //printUtil.UsbPrintStringTitle(Properties.Settings.Default.save_print_title + "\n");
                        int print_nums = 1;


                        print_nums = mVips.Count > 0 ? Properties.Settings.Default.save_print_vip_nums : Properties.Settings.Default.save_print_normal_nums;
                        

                        while(print_nums>0){
                            print_nums--;
                            printUtil.UsbPrintString("　　　　　　" + Properties.Settings.Default.save_print_title + "\n.\n" + GetPrintStr(checkOuts, checkOutGzs, true));                  
                        }
                        print_flag = false;
                    }
                    catch
                    {
                        string messageBoxText1 = "已结账成功，但打印出错，请检查打印机是否正确连接或者打印机名称是否为\"XP-80\"!\n点“是”重试";
                        string caption1 = "打印出错";
                        MessageBoxButton button1 = MessageBoxButton.YesNo;
                        MessageBoxImage icon1 = MessageBoxImage.Warning;
                        MessageBoxResult result1 = MessageBox.Show(messageBoxText1, caption1, button1, icon1);
                        if (result1 == MessageBoxResult.No)
                            print_flag = false;

                    }
                }
                //MessageBox.Show(GetPrintStr(checkOuts, checkOutGzs));

                this.DialogResult = true;
                this.Close();
            }
        }

        public string GetPrintStr(List<CheckOut> checkOuts, List<CheckOutGz> checkOutGzs, bool isCheckout)
        {
            string str = "";
            Order order = isCheckout?App.OrderBean.GetHisOrderByOrderNum(checkOuts[0].Order_num):App.OrderBean.GetOrderByOrderNum(checkOuts[0].Order_num);
            StringUtil strUtil = new StringUtil();

            str += "账单号：" + checkOuts[0].Checkout_num + "\n";
            str += "收银员：" + App.user.Uname + "\n";
            str += "服务员：" + App.UserBean.GetUserByField("user_num", order.User_num) + "\t\t人数:" + order.Size + "\n";
            str += "桌位：";
            foreach (CheckOut c in checkOuts)
            {
                str += App.TabBean.GetTabByField("tab_num", c.Tab_num + "").Name + " ";
            }

            str += "\n点餐：" + order.Time + "\n";
            if (isCheckout)
                str += "结账：" + System.DateTime.Now.ToString("yyyy/M/d HH:mm:ss") + "\n";
            str += "\n";



            str += strUtil.FillStr("品名", 7, "　") + strUtil.FillStr("数量", 3, "　") + strUtil.FillStr("单位", 3, "　") + strUtil.FillStr("单价", 4, "　") + strUtil.FillStr("总额", 4, "　") + "\n";
            str += "------------------------------------------\n";
            foreach (Order o in mOrders)
            {
                if (o.Together_name != "")
                {
                    str += "套餐：" + o.Together_name + "(" + App.TogetherBean.GetTogetherByField("name", o.Together_name).Price + "元)\n";
                    DataTable tg_table = App.TogetherBean.GetOrdersByName(o.Together_name);
                    for (int i = 0; i < tg_table.Rows.Count; i++)
                    {
                        str += strUtil.FillStr(tg_table.Rows[i]["品名"].ToString(), 8, "　");
                        str += strUtil.FillStr(tg_table.Rows[i]["数量"].ToString(), 3, "　");
                        str += strUtil.FillStr(tg_table.Rows[i]["单位"].ToString(), 3, "　");
                        str += strUtil.FillStr(tg_table.Rows[i]["单价（元）"].ToString(), 5, "　");

                        str += "\n";
                    }

                }
            }
            str += "------------------------------------------\n";
            DataTable dt = isCheckout?App.OrdersBean.GetHisOrdersDataTableByOrderNum(mOrder_nums):App.OrdersBean.GetOrdersDataTableByOrderNum(mOrder_nums);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                str += strUtil.FillStr(dt.Rows[i]["品名"].ToString(), 8, "　");
                str += strUtil.FillStr(dt.Rows[i]["数量"].ToString(), 3, "　");
                str += strUtil.FillStr(dt.Rows[i]["单位"].ToString(), 3, "　");
                str += strUtil.FillStr(dt.Rows[i]["单价（元）"].ToString(), 5, "　");
                str += strUtil.FillStr(dt.Rows[i]["总额（元）"].ToString(), 4, "　");

                str += "\n";
            }
            DataTable returned_dt = isCheckout ? App.OrdersBean.GetHisReturnedOrdersDataTableByOrderNum(mOrder_nums) : App.OrdersBean.GetReturnedOrdersDataTableByOrderNum(mOrder_nums);
            if (returned_dt.Rows.Count > 0)
            {
                for (int i = 0; i < returned_dt.Rows.Count; i++)
                {
                    str += "[退]" + returned_dt.Rows[i]["品名"].ToString().PadRight(12, ' ');
                    str += ("-" + returned_dt.Rows[i]["数量"].ToString() + returned_dt.Rows[i]["单位"].ToString() + "(共:" + returned_dt.Rows[i]["总额"].ToString() + "元)").PadRight(3, ' ');
                    str += "\n";
                }
            }

            if (dt.Rows.Count > 0)
                str += "------------------------------------------\n";

            str += "小\t计：" + checkOuts[0].Sum + " 元\n";
            if (!isCheckout)
            {
               // MessageBox.Show(str);   //FORDEBUG
                return str += "\n.\n.\n.\n.\n";
            }
            str += "优惠：" + checkOuts[0].Sub_sum + " 元";

            str += "(抹零：" + mTemp_ml_j + " 元)";

            if (checkOuts[0].Sub_sum > 0)
                str += "\t批准人：" + App.UserBean.GetUserByField("user_num", checkOuts[0].Approver);
            str += "\n";
            str += "赔偿："+txt_pc.Text+" 元\n";
            str += "应收金额：" + (checkOuts[0].Sum - checkOuts[0].Sub_sum) + " 元\n";

            str += "------------------------------------------\n";
            if (checkOutGzs[0] != null)
            {
                str += "挂账信息：" + checkOutGzs[0].Sign_name + "(" + checkOutGzs[0].Department + ")\n";
            }
            else
            {
                if (checkOuts[0].Cash_sum != 0)
                {
                    str += "现金：" + txt_cash.Text + "元\n";
                }
                if (checkOuts[0].Djq_sum != 0)
                    str += "代金券：" + txt_djq.Text + "元 ";
                if (checkOuts[0].Tgq_sum != 0)
                    str += "团购券：" + txt_tgq.Text + "元 ";
                if (checkOuts[0].Xyk_sum != 0)
                    str += "信用卡：" + txt_xyk.Text + "元 ";
                if (checkOuts[0].Hyk_sum != 0)
                {
                    str += "会员卡：" + txt_hyk.Text + "元 \n";
                    foreach(string s in  mVips){
                        str += s + "\n";
                    }
                }
                str += "\n找零：" + txt_return_cash.Text + " 元\n";
            }
            str += "------------------------------------------\n";
            //MessageBox.Show(str);   //FORDEBUG
            return str + Properties.Settings.Default.save_print_foot + "\n.\n.\n.\n.\n";
        }



        /// <summary>
        /// 获得当前结账单的实体
        /// </summary>
        /// <returns>返回null代表填写不完整</returns>
        public List<CheckOut> GetCheckOut()
        {
            float ml_sum = 0;
            if (cb_ml.IsChecked == true)
            {
                ml_sum = mTemp_ml;
            }
            List<CheckOut> checkOuts = new List<CheckOut>();
            for (int i = 0; i < list_order_id.Count; i++)
            {
                checkOuts.Add(new CheckOut());
            }
            //整单优惠
            if (cb_main_discount_type.SelectedIndex == 0)
            {
                foreach (CheckOut co in checkOuts)
                {
                    co.Sub_sum = 0;
                }
                checkOuts[0].Sub_sum = float.Parse(discount_money.Text) + ml_sum + mTemp_ml_j;
            }
            //按种类优惠
            if (cb_main_discount_type.SelectedIndex == 1)
            {
                foreach (CheckOut co in checkOuts)
                {
                    co.Sub_sum = 0;
                }
                checkOuts[0].Sub_sum = float.Parse(discount_money.Text) + ml_sum;
            }
            foreach (CheckOut co in checkOuts)
            {
                if (co.Sub_sum > 0)
                    co.Approver = ((User)cb_approver.SelectedItem).User_num;
                co.Checkout_num = txt_checkout_num.Text;
            }

            for (int i = 0; i < checkOuts.Count; i++)
            {
                checkOuts[i].Order_num = mOrder_nums[i];
                checkOuts[i].Tab_num = mTab_nums[i];

                if (i == 0)
                {

                    checkOuts[i].Djq_sum = float.Parse(txt_djq.Text);
                    checkOuts[i].Tgq_sum = float.Parse(txt_tgq.Text);
                    checkOuts[i].Xyk_sum = float.Parse(txt_xyk.Text);
                    checkOuts[i].Hyk_sum = float.Parse(txt_hyk.Text);

                    checkOuts[i].Pc_sum = float.Parse(txt_pc.Text);

                    checkOuts[i].Cash_sum = float.Parse(txt_cash.Text) - float.Parse(txt_return_cash.Text);
                    checkOuts[i].Drink_sum = float.Parse(txt_jsyl_price.Text);
                    checkOuts[i].Food_sum = mTrue_sum - checkOuts[i].Drink_sum - checkOuts[i].Pc_sum;   //要把赔偿的也去掉
                    checkOuts[i].Sum = mTrue_sum;
                    checkOuts[i].Final_cash = Convert.ToInt32(Math.Round(mTrue_sum - checkOuts[i].Sub_sum, 0));
                }
                else
                {
                    checkOuts[i].Cash_sum = 0;
                    checkOuts[i].Djq_sum = 0;
                    checkOuts[i].Tgq_sum = 0;
                    checkOuts[i].Pc_sum = 0;
                    checkOuts[i].Xyk_sum = 0;
                    checkOuts[i].Hyk_sum = 0;
                    checkOuts[i].Drink_sum = 0;
                    checkOuts[i].Food_sum = 0;
                    checkOuts[i].Sum = 0;
                    checkOuts[i].Final_cash = 0;
                }
            }


            return checkOuts;
        }

        /// <summary>
        /// 总的优惠方式变化,默认选择第一项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cb_main_discount_type_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                txt_all_final_price.Text = txt_sum.Text.Split('.')[0];
                discount_money.Text = "0";
                discount_byrate.Text = "";
            }
            catch { }
            //整单优惠
            if (((ComboBox)sender).SelectedIndex == 0)
            {
                try
                {
                    discount_type_rate.IsChecked = true;
                }
                catch { }
            }//种类优惠
            else if (((ComboBox)sender).SelectedIndex == 1)
            {
                try
                {
                    sp_food_type.Children.Clear();
                    for (int i = 0; i < mFood_type.Count; i++)
                    {
                        StackPanel sp1 = new StackPanel();
                        sp1.Orientation = Orientation.Horizontal;
                        sp1.Margin = new Thickness(2);

                        TextBlock tb1 = new TextBlock();
                        tb1.Margin = new Thickness(0, 0, 5, 0);
                        tb1.Text = mFood_type[i];
                        sp1.Children.Add(tb1);

                        TextBox tbox = new TextBox();
                        tbox.Tag = mFood_type[i];
                        tbox.Width = 60;
                        tbox.Text = "100";
                        sp1.Children.Add(tbox);
                        tbox.TextChanged += discountbytype_TextChanged;

                        sp_food_type.Children.Add(sp1);
                    }
                }
                catch { }
            }
        }

        /// <summary>
        /// 关闭按钮
        /// </summary>
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            this.Close();
        }



        /// <summary>
        /// 1。折扣率等变化，引发优惠金额变化
        /// </summary>
        private void discount_byrate_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (discount_byrate.Text != "")
                discount_money.Text = strUtil.Round(mTrue_sum * (1f - float.Parse(discount_byrate.Text) * 0.01f), 1) + "";
            else
                discount_money.Text = "0";
        }

        private void discount_bymoney_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (discount_bymoney.Text != "")
                    discount_money.Text = float.Parse(discount_bymoney.Text) + "";
                else
                    discount_money.Text = "0";
            }
            catch
            {
                MessageBox.Show("输入有误！");
                discount_bymoney.Text = "";
            }
        }

        private void discount_byfinalmoney_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (discount_byfinalmoney.Text != "")
                discount_money.Text = strUtil.Round((mTrue_sum - float.Parse(discount_byfinalmoney.Text)), 1) + "";
            else
                discount_money.Text = "0";
        }

        /// <summary>
        /// 2。优惠金额变化，引发应收金额变化，再引发找零变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void discount_money_TextChanged(object sender, TextChangedEventArgs e)
        {
            cb_ml.IsChecked = false;
            if (float.Parse(discount_money.Text) > 0)
            {
                pb_pwd.IsEnabled = true;
                cb_approver.IsEnabled = true;
            }
            else
            {
                pb_pwd.IsEnabled = false;
                cb_approver.IsEnabled = false;
            }

            txt_all_final_price.Text = (strUtil.Round((mTrue_sum - float.Parse(discount_money.Text)), 1) + "").Split('.')[0];
            refresh_return_cash();
        }

        /// <summary>
        /// x。实收现金变化，引发找零变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cashorother_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            string pattern = @"^\d+\.?\d+$";
            string pattern1 = @"^\d+$";
            string content = ((TextBox)sender).Text;
            if (!(Regex.IsMatch(content, pattern1)) && !(Regex.IsMatch(content, pattern)))
            {
                // if (content == "" || content.IndexOf(' ')!=-1)
                MessageBox.Show("金额必须是数字！");
                ((TextBox)sender).Focus();
                btn_checkout.IsEnabled = false;
                btn_print.IsEnabled = false;
            }
            else
            {
                try
                {
                    btn_checkout.IsEnabled = true;
                    btn_print.IsEnabled = true;
                    /*if (((TextBox)sender).Name == "txt_djq")   //代金券特殊处理，只能支付其它
                    {

                        if (float.Parse(txt_djq.Text) > float.Parse(txt_qt_price.Text))
                        {
                            effect_djq.Text = txt_qt_price.Text;
                            effect_djq_sp.Visibility = Visibility.Visible;
                        }
                        else
                        {
                            effect_djq.Text = txt_djq.Text;
                            effect_djq_sp.Visibility = Visibility.Collapsed;
                        }
                    }
                    if (((TextBox)sender).Name == "txt_tgq")   //团购券特殊处理，只能支付其它
                    {

                        if (float.Parse(txt_tgq.Text) > float.Parse(txt_qt_price.Text))
                        {
                            effect_tgq.Text = txt_qt_price.Text;
                            effect_tgq_sp.Visibility = Visibility.Visible;
                        }
                        else
                        {
                            effect_tgq.Text = txt_tgq.Text;
                            effect_tgq_sp.Visibility = Visibility.Collapsed;
                        }
                    }*/
                    if (((TextBox)sender).Name == "txt_djq")   //代金券特殊处理，只能支付其它
                    {
                        effect_djq.Text = txt_djq.Text;
                    }
                    if (((TextBox)sender).Name == "txt_tgq")   //代金券特殊处理，只能支付其它
                    {
                        effect_tgq.Text = txt_tgq.Text;
                    }
                    if (((TextBox)sender).Name == "txt_hyk")   //会员卡特殊处理，只能支付其它和酒水饮料
                    {
                        if (float.Parse(txt_hyk.Text) > (float.Parse(txt_qt_price.Text)+float.Parse(txt_jsyl_price.Text)))
                        {
                            txt_effecthyk.Text = (float.Parse(txt_qt_price.Text) + float.Parse(txt_jsyl_price.Text))+"";
                        }
                        else
                        {
                            txt_effecthyk.Text = txt_hyk.Text;
                        }
                    }
                }
                catch { }
                refresh_return_cash();
            }
        }

        /// <summary>
        /// 整单优惠.优惠方式发生变化时，初始化 优惠额，至第1步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void discount_type_Checked(object sender, RoutedEventArgs e)
        {
            if (discount_byrate != null)
                discount_byrate.Text = "";
            if (discount_bymoney != null)
                discount_bymoney.Text = "";
            if (discount_byfinalmoney != null)
                discount_byfinalmoney.Text = "";
        }

        public void refresh_return_cash()
        {
            try
            {
               /* double effect_djq_sum = 0;
                if (effect_djq_sp.Visibility == Visibility.Visible)
                    effect_djq_sum = double.Parse(effect_djq.Text);
                else
                    effect_djq_sum = double.Parse(txt_djq.Text);
                txt_return_cash.Text = strUtil.Round((double.Parse(txt_cash.Text) + effect_djq_sum + double.Parse(txt_xyk.Text) + double.Parse(txt_effecthyk.Text) - double.Parse(txt_all_final_price.Text)), 1).ToString();
            */
                double effect_q_sum = 0;
                double djq_sum = double.Parse(effect_djq.Text);
                double tgq_sum = double.Parse(effect_tgq.Text);
                effect_q_sum = djq_sum+tgq_sum;
                double qt_price = double.Parse(txt_qt_price.Text);
                if (effect_q_sum > qt_price)
                {
                    effect_q_sum = qt_price;
                }
                txt_return_cash.Text = strUtil.Round((double.Parse(txt_cash.Text) + effect_q_sum + double.Parse(txt_xyk.Text) + double.Parse(txt_effecthyk.Text) - double.Parse(txt_all_final_price.Text)), 1).ToString();
           
            }
            catch { }
        }

        private void txt_all_final_price_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                refresh_return_cash();
            }
            catch { }
        }


        public T GetChildObject<T>(DependencyObject obj, string tag) where T : FrameworkElement
        {
            DependencyObject child = null;
            T grandChild = null;

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T && (((T)child).Tag == tag | string.IsNullOrEmpty(tag)))
                {
                    return (T)child;
                }
                else
                {
                    grandChild = GetChildObject<T>(child, tag);
                    if (grandChild != null)
                        return grandChild;
                }
            }
            return null;
        }

        private void discountbytype_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                float dis_sum = 0;
                for (int i = 0; i < mFood_type.Count; i++)
                {
                    int dis = Int32.Parse(((TextBox)GetChildObject<TextBox>(sp_food_type, mFood_type[i])).Text);
                    dis_sum += (App.OrdersBean.GetAllPriceByOrderNumOrType(mOrder_nums, mFood_type[i]) - App.OrdersBean.GetAllReturnedSumByOrderNumAndType(mOrder_nums, mFood_type[i])) * (100 - dis) * 0.01f;
                }
                discount_money.Text = strUtil.Round(dis_sum, 1) + "";
            }
            catch { }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            if (App.GzBean.GetAllGz().Count == 0)
            {
                MessageBox.Show("没有挂账人信息，请先添加！");
                return;
            }
            checkOutGzs[0] = new CheckOutGz();
            CheckOutGzDlg win = new CheckOutGzDlg(checkOutGzs[0]);
            win.ShowDialog();
            if (win.DialogResult == false)
            {
                checkOutGzs[0] = null;
            }
            if (checkOutGzs[0] != null)
            {
                txt_gz_info.Text = checkOutGzs[0].Sign_name + "(" + checkOutGzs[0].Department + ")";
            }
            else
            {
                txt_gz_info.Text = "无";
            }
            for (int i = 1; i < checkOutGzs.Count; i++)
            {
                checkOutGzs[i].Sign_name = checkOutGzs[0].Sign_name;
                checkOutGzs[i].Department = checkOutGzs[0].Department;
                checkOutGzs[i].Phone = checkOutGzs[0].Phone;
                checkOutGzs[i].Doer = checkOutGzs[0].Doer;
                checkOutGzs[i].Approver = checkOutGzs[0].Approver;
            }
        }

        private void cb_ml_Click(object sender, RoutedEventArgs e)
        {
            if (cb_ml.IsChecked == true)
            {
                pb_pwd.IsEnabled = true;
                cb_approver.IsEnabled = true;

                mTemp_ml = float.Parse(txt_all_final_price.Text) - (int)Convert.ToDouble(txt_all_final_price.Text) / 10 * 10;
                txt_all_final_price.Text = (int)Convert.ToDouble(txt_all_final_price.Text) / 10 * 10 + "";
            }
            else if (cb_ml.IsChecked == false)
            {
                //mTemp_ml = 0;
                txt_all_final_price.Text = (float.Parse(txt_all_final_price.Text) + mTemp_ml) + "";

                if (float.Parse(discount_money.Text) == 0)
                {
                    pb_pwd.IsEnabled = false;
                    cb_approver.IsEnabled = false;
                }
            }
        }

        //连接读卡器设备
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {

            if (OptCard.icdev <= 0)
            {
                try
                {
                    if (OptCard.ConnectDev())//连接成功
                    {
                        OptCard.BeepTip();
                    }
                    else
                    {
                        MessageBox.Show("连接失败！");
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("请检查读卡器是否正常连接！");
                    return;
                }
            }
            else if(cardFlag)
            {
                OptCard.ConnectDev();
            }
            
            //MessageBox.Show(OptCard.icdev+"");
            if (!OptCard.SeekCard()) //寻卡
            {
                OptCard.BeepTip();
                MessageBox.Show("寻卡失败！");
                return;
            }

            string isn = OptCard.GetISN(); //寻卡成功，返回卡的序列号         
            //（通过卡ISN）查询数据库中是否发行过此卡
            if (CardDAL.GetAllByISN(isn).Length <= 0)
            {
                MessageBox.Show("此卡非本店发行！");
                return;
            }

            if (!OptCard.ChooseCard()) //卡片多选一失败
            {
                MessageBox.Show("多卡选一卡失败！");
                return;
            }

            //验证卡密码，写卡
            string pass = OptCard.NewPass;

            //装载密码到读写器的RAM中，并验证密码
            if (!OptCard.CheckPassword(pass, 1)) //密码，扇区号
            {
                MessageBox.Show("IC卡密码错误");
                return;
            }

            //读取卡中的信息(卡号，余额)
            string cardID = OptCard.ReadMemberID(1);
            string balance = OptCard.ReadRestMoney(1);//OptCard中函数已经转换角到元了

            float CardBalance = float.Parse(balance);
            //根据卡号从数据库中查出，姓名，电话，余额
            card = CardDAL.GetById(cardID);

            float DataBalance = card.Balance;
            //比对卡中余额是否和数据库中一致       
            if (!(CardBalance == DataBalance))
            {
                MessageBox.Show("卡中余额与数据库不一致");
                return;
            }

            if (card.Status != 0)
            {
                MessageBox.Show("此卡已冻结，无法使用！");
                return;
            }

            txt_cardid.Text = cardID;
            txt_balance.Text = balance;

            txt_cardmoney.IsEnabled = true;
            txt_cardmoney.Focus();
            if (txt_return_cash.Text.IndexOf('-') != -1)
            {
                if (float.Parse(txt_return_cash.Text.Split('-')[1]) > CardBalance)
                    txt_cardmoney.Text = CardBalance+"";
                else
                    txt_cardmoney.Text = txt_return_cash.Text.Split('-')[1];
                
            }
            else
                txt_cardmoney.Text = "0";
            txt_cardmoney.SelectAll();
            btn_kc.Visibility = Visibility.Visible;
            btn_qx.Visibility = Visibility.Visible;
            btn_dk.Visibility = Visibility.Collapsed;
            sp_cardinfo.Visibility = Visibility.Visible;

            cardFlag = false;
        }


        

        private void btn_kc_Click(object sender, RoutedEventArgs e)
        {
            float cardSum = 0;
            float cardBalance = 0;

            if (card == null)
            {
                MessageBox.Show("请先读卡后扣除！");
                return;
            }
            if (card.Status != 0)
            {
                MessageBox.Show("此卡已冻结，无法扣除！");
                return;
            }
            if (!(OptCard.icdev > 0))
            {
                MessageBox.Show("未连接读卡器！");
                return;
            }
            if (!OptCard.SeekCard()) //寻卡
            {
                OptCard.BeepTip();
                MessageBox.Show("寻卡失败！");
                return;
            }
            string isn = OptCard.GetISN(); //寻卡成功，返回卡的序列号

            if (!OptCard.ChooseCard()) //卡片多选一失败
            {
                MessageBox.Show("多卡选一卡失败！");
                return;
            }

            //验证卡密码，写卡
            string pass = OptCard.NewPass;

            //装载密码到读写器的RAM中，并验证密码
            if (!OptCard.CheckPassword(pass, 1)) //密码，扇区号
            {
                MessageBox.Show("IC卡密码错误");
                return;
            }


            try
            {
               cardSum = float.Parse(txt_cardmoney.Text);
               cardBalance = float.Parse(txt_balance.Text);
               if (cardSum <= 0 || cardSum > cardBalance)
               {
                   MessageBox.Show("输入金额不可以大于卡余额或为零！");
                   return;
               }
            }
            catch
            {
                MessageBox.Show("输入金额有误！");
                return;
            }

            float balance_for_print = card.Balance;
            card.Balance -= cardSum; //更改了卡的余额

            //创建消费记录对象
            Consume record = new Consume();
            record.MemCardID = card.MemCardID;
            record.Money = cardSum;
            record.Date = DateTime.Now;
            record.Operator = App.user.Uname;
            record.Type = 2;//类型2是消费
            record.ConsumeShopNum = "总店01";

            if (OptCard.DeRestMoney(cardSum + "", 1) && ConsumeDAL.Insert(record) > 0 && CardDAL.Update(card) > 0 && ConsumeDAL.updatePoints(Int32.Parse(cardSum + ""), record.MemCardID) > 0 && ConsumeDAL.insertPointLog(record)>0)
            {
                OptCard.BeepTip();
                MessageBox.Show("扣除成功");
                txt_balance.Text = card.Balance + "";
                txt_hyk.Text = (float.Parse(txt_hyk.Text) + cardSum) + "";

                mVips.Add("卡号:" + record.MemCardID + " 消费:" + cardSum + " 余额:" + card.Balance + " 积分:" + CustomerDAL.GetById(record.MemCardID).Points);
                txt_cardmoney.Text = "0";
                txt_cardmoney.IsEnabled = false;
                btn_dk.Visibility = Visibility.Visible;
                btn_kc.Visibility = Visibility.Collapsed;
                btn_qx.Visibility = Visibility.Collapsed;
               // sp_cardinfo.Visibility = Visibility.Collapsed;
            }
            else
            {
                MessageBox.Show("扣除失败");
                return;
            }
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            txt_cardmoney.Text = "0";
            txt_cardmoney.IsEnabled = false;
            btn_dk.Visibility = Visibility.Visible;
            btn_kc.Visibility = Visibility.Collapsed;
            btn_qx.Visibility = Visibility.Collapsed;
            sp_cardinfo.Visibility = Visibility.Collapsed;
        }


        private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                //MessageBox.Show(OptCard.icdev + "");
                if (OptCard.DisConnectDev())
                {
                    //MessageBox.Show("断开失败！这有可能导致下次无法读卡！请重新打开任意结账窗口并关闭");
                }
            }
            catch { }
        }

        private void pb_pwd_LostFocus(object sender, RoutedEventArgs e)
        {
            if (pb_pwd.IsEnabled)
            {
                if (App.UserBean.VerifyUser(((User)cb_approver.SelectedItem).User_num, pb_pwd.Password) == 0)
                {
                    MessageBox.Show(((User)cb_approver.SelectedItem).User_num + ",授权密码错误！");
                    return;
                }

            }
        }

        private void txt_pc_TextChanged(object sender, TextChangedEventArgs e)
        {
            string pattern = @"^\d+\.?\d+$";
            string pattern1 = @"^\d+$";
            string content = ((TextBox)sender).Text;
            if (!(Regex.IsMatch(content, pattern1)) && !(Regex.IsMatch(content, pattern)))
            {
                // if (content == "" || content.IndexOf(' ')!=-1)
                MessageBox.Show("赔偿金额必须是大于等于0的数字！");
                ((TextBox)sender).Focus();
                btn_checkout.IsEnabled = false;
                btn_print.IsEnabled = false;

                mTrue_sum = mTrue_sum_backup;
                txt_all_final_price.Text = mTrue_sum + "";
                mPc_sum = 0;
            }
            else
            {
                
                txt_all_final_price.Text = (float.Parse(txt_all_final_price.Text) + (float.Parse(content)-mPc_sum))+"";
                mPc_sum = float.Parse(content);   //一定要放在上一句的下面
                mTrue_sum = float.Parse(txt_all_final_price.Text);
                try
                {
                    btn_checkout.IsEnabled = true;
                    btn_print.IsEnabled = true;
                }
                catch { }
            }
        }
    }


    
}
